package com.topInterview;

import java.util.HashMap;
import java.util.Map;

/**
 * 给定一个字符串 s ，请你找出其中不含有重复字符的 最长子串 的长度
 *
 * @Author: huangzhigao
 * @Date: 2022/2/12 20:24
 */
public class Leetcode3_LongestSubStringLen {

    public static int lengthOfLongestSubstring(String s) {
        char[] chars = s.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        int res = 0;
        int start = 0;
        for (int end = 0; end < chars.length; end++) {
            if (map.containsKey(chars[end])) {
                start = Math.max(start, map.get(chars[end]));
            }
            map.put(chars[end], end + 1);
            res = Math.max(res, end - start + 1);
        }
        return res;
    }


    public static int ways2(String s) {
        char[] chars = s.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        //pre代表i-1位置，向前推不动的位置
        int pre = -1;
        int res = 0;
        int cur = 0;
        for (int i = 0; i < chars.length; i++) {
            pre = Math.max(pre, map.get(chars[i]));
            cur = i - pre;
            res = Math.max(res, cur);
            map.put(chars[i], i);
        }

        return res;
    }


    public static void main(String[] args) {
        String s = "ab";
        System.out.println(lengthOfLongestSubstring(s));
    }
}
